package cn.itcast.controller;


import cn.hutool.http.server.HttpServerResponse;
import cn.itcast.service.RedisService;
import cn.itcast.util.CaptchaUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.annotations.Param;
import cn.itcast.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.plaf.PanelUI;

@RestController
@RequestMapping("captcha")
@CrossOrigin(maxAge = 3600)
public class CaptchaController {

    @Autowired
    CaptchaUtil captchaUtil;

    @Autowired
    RedisService redisService;
    @RequestMapping("base")
    public Result getCaptcha(HttpServletResponse response){
        String[] arr= captchaUtil.getImage();
        String key=arr[0];
        String base64=arr[1];
        jakarta.servlet.http.Cookie cookie=new jakarta.servlet.http.Cookie("captchakey",key);
        response.addCookie(cookie);
        return Result.success("已经更新验证码","data:image/jpeg;base64,"+base64);
    }

    @RequestMapping("check")

    public Result checkCaptcha(HttpServletRequest request, @RequestParam("captchacode") String captchacode){
        Cookie[] cookies=request.getCookies();
        String key=null;
        for(Cookie cookie:cookies){
            if(cookie.getName().equals("captchakey")){
                key=cookie.getValue();
                break;
            }
        }
        if(key==null){
            return Result.fail(400,"请求参数异常");
        }
        String code=(String)redisService.get(key);
        if(code==null){
            return Result.fail(201,"验证码已过期");
        }
        if(captchacode.equals(code)){
            return Result.success("验证码正确",true);
        }
        return Result.fail(400,"验证失败");
    }
}
